<template>
    <Modal
        v-model="modal.show"
        :title="modal.title"
        :loading="modal.loading"
        :width="1000"
        @on-ok="saveTask"
        @on-cancel="hideModal"
    >
    <Form ref="formValidate" :model="formValidate" :label-width="80" :rules="ruleValidate">
        <FormItem label="任务名称" prop="taskName">
            <Input
                v-model="formValidate.taskName"
                :maxlength="64"
                :placeholder="nameErrorTip"
            ></Input>
        </FormItem>
        <FormItem label="任务时间" prop="time">
            <FormDatepicker v-model="formValidate.time" placeholder="请选择任务时间" style="width:100%;"></FormDatepicker>
        </FormItem>
        <FormItem label="描述" prop="description">
            <Input
                type="textarea"
                v-model="formValidate.description"
                :maxlength="200"
                placeholder="请输入描述"
            ></Input>
        </FormItem>
        <FormItem label="分配设备" prop="deviceTOList">
            <TableList 
                :columns="deviceCol"
                :data="deviceData"
                :total="deviceTotal"
                :page.sync="queryDevice.pageIndex"
                :size.sync="queryDevice.pageSize"
                :selection.sync="formValidate.deviceTOList"
                showSelectTag
                @queryFun="getVmList"
            >
            </TableList>
        </FormItem>
    </Form>
    </Modal>
</template>
<script>
import {
    addTask,
    updateTask,
} from '../../api/task.js';
import { getAllVm } from '@/api/drill.js'
import { mapState } from 'vuex';
import { validateName1, nameErrorTip  } from '@/libs/reg';
import FormDatepicker from '@/components/common/form-datepicker'
export default {
    name: 'EditModal',
    components: { FormDatepicker }, //FormModal
    // mixins: [formDataMixin], //treeDirectionData
    // inject: ['parent'],
    props: {
        title: {
            type: String,
            default: '任务',
        },
        projectId:{
            type: String,
            default: '',
        },
        contentId:{
            type: String,
            default: '',
        }
    },
    data() {
        return {
            nameErrorTip,
            modal: {
                show: false,
                data: '',
                loading: true,
            },
            selectedDevices:[],
            formValidate:{
                projectId:this.projectId,
                contentId:this.contentId,
                taskName:'',
                time:[],
                description:'',
                deviceTOList:[]
            },
            ruleValidate: {
                taskName: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { validator: validateName1, trigger: 'change, blur' },
                ],
                time:{
                    type:'array',
                    min:2,
                    max:2,
                    message: '请选择任务时间'
                }
            },
            deviceCol: [
                {
                    type: 'selection',
                    width:60
                },
                {
                    title: '虚拟机名称',
                    key: 'name',
                    minWidth: 50,
                    tooltip: true,
                },
                {
                    title: 'IP',
                    key: 'ipAddress',
                    minWidth: 50,
                    tooltip: true,
                    render: (h, params) => {
                        let _this = this;
                        params = params.row;
                        let addresses = [];
                        if (params.addresses) {
                            if (params.addresses.length != 0) {
                                addresses = params.addresses.map((item) => {
                                    //                                          return h('div',{},item.ip);
                                    let ips = item.ips.map((ip) => {
                                        return h('div', {}, ip.ipAddress);
                                    });
                                    return h('div', {}, ips);
                                });
                                return h('div', {}, addresses);
                            }
                        }
                    },
                },
                {
                    title: '用户名',
                    key: 'username',
                    minWidth: 50,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0 ? data.accesses[0].username : '-';
                    },
                },
                {
                    title: '密码',
                    key: 'password',
                    minWidth: 50,
                    tooltip: true,
                    filter: (accesses, data) => {
                        return data.accesses.length > 0 ? data.accesses[0].password : '-';
                    },
                },
                // {
                //     title: '接入类型',
                //     key: 'accessType',
                //     minWidth: 50,
                //     tooltip: true,
                //     filter: (accesses, data) => {
                //         return data.accesses.length > 0
                //             ? data.accesses.map((item) => item.accessType).join(',')
                //             : '-';
                //     },
                // },
                {
                    title: '操作系统类型',
                    key: 'sysType',
                    minWidth: 50,
                    tooltip: true,
                },
                {
                    title: '镜像名称',
                    key: 'imageName',
                    minWidth: 50,
                    tooltip: true,
                }
            ],
            deviceData:[],
            deviceTotal:0,
            queryDevice:{
                projectId:this.projectId,
                pageIndex:1,
                pageSize:10
            }
        };
    },
    computed: {
        // ...mapState('user', ['nickname', 'userId', 'isRootDesigner'])
    },
    watch: {
        
    },
    mounted() {
        this._formValidate = {...this.formValidate}
        this.getVmList()
    },
    methods: {
        showModal(data,user) {
            let name = this.title;
            this.taskUserId = user.userId;
            this.modal.show = true;
            this.op = data ? 'update' : 'add';
            if (!data) {
                this.modal.title = `创建${name}`;
                this.resetField();
            } else {
                this.modal.title = `修改${name}`;
                this.formValidate = {...data,time:[data.startTime,data.endTime],deviceTOList:data.deviceTOS.map(device => {
                    return {
                        id:device.deviceId,
                        name:device.deviceName
                    }
                })};
            }
        },
        resetField() {
            this.formValidate = {...this._formValidate};
            this.$refs.formValidate.resetFields();
        },
        saveTask() {
            this.$refs.formValidate.validate((valid) => {
                if (valid) {
                    let params = { ...this.formValidate };
                    params.startTime = params.time[0];
                    params.endTime = params.time[1];
                    params.deviceTOList = params.deviceTOList.map((device) => {
                        return {
                            deviceId:device.id,
                            deviceName:device.name
                        }
                    })
                    params.userId = this.taskUserId
                    delete params.time;
                    let reqApi, txt;
                    if (this.op == 'add') {
                        reqApi = addTask(params);
                        txt = '创建';
                    } else {
                        reqApi = updateTask(params.id, params);
                        txt = '修改';
                    }
                    reqApi
                        .then(({ code, data, message }) => {
                            if (code === 1) {
                                this.$Message.info(`${txt}成功`);
                                this.hideModal();
                                this.$emit('ok', this.op);
                            } else {
                                this.$Message.error(message);
                            }
                            this.cancelLoading();
                        })
                        .catch((error) => {
                            this.cancelLoading();
                        });
                } else {
                    this.cancelLoading();
                }
            });
        },
        hideModal() {
            this.modal.show = false;
        },
        cancelLoading() {
            this.modal.loading = false;
            setTimeout(() => {
                this.modal.loading = true;
            });
        },
        getVmList(){
            getAllVm(this.queryDevice).then((response)=>{
                if(response.code == 1){
                    let vmData = response.data.items;
                    this.deviceTotal = Number(response.data.total);
                    vmData.forEach(function(item,i){
                        item.IP = item.addresses.map((item)=>item.ips.map(ip => ip.ipAddress).join(','))
                    })
                    this.deviceData = vmData;
                }else{
                    this.deviceData = [];
                    this.deviceTotal = 0;
                    this.$Message.error(response.message)
                }
            })
        }
    },
};
</script>
<style scoped></style>
